package com.jinghua.treatment.websocket;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;


public class PresenceChannelInterceptor extends ChannelInterceptorAdapter {

    Logger  log   = Logger.getLogger(PresenceChannelInterceptor.class);

    @Autowired
    SocketSessionRegistry webAgentSessionRegistry;
    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(message);
        if (sha.getCommand() == null) {
            return;
        }

        switch (sha.getCommand()) {
            case CONNECT:
                log.debug("user connect");
                checkin(sha);
                break;
            case CONNECTED:
                log.debug("connect success");
                break;
            case DISCONNECT:
                log.debug("user offline");
                checkout(sha);
                break;
            default:
                break;
        }
    }

    private void checkin(StompHeaderAccessor sha){
        String agentId = sha.getNativeHeader("login").get(0);
        String sessionId = sha.getSessionId();
        webAgentSessionRegistry.registerSessionId(agentId,sessionId);
        log.debug("user ["+agentId+"] check in done!");

    }

    private void checkout(StompHeaderAccessor sha){
        String sessionId = sha.getSessionId();
        webAgentSessionRegistry.unregisterSessionId(sessionId);
        log.debug("user ["+sha.getSessionId()+"] check out done!");
    }

}